<template>
  <div class="user-login">    
    <template v-if="!scanCodeBoolean">
      <img class="img-logo" :src="appInfo.appLogo" alt="" v-if="appInfo.appLogo">
      <div v-if="leaderApply" class="font-22 font-w text-align-c" style="margin-top: 100px;">申请社区团购团长</div>
      <div v-if="storeApply" class="font-22 font-w text-align-c" style="margin-top: 100px;">
        <div>授权后成为总部直营门店</div>
        <div>社区团购团长</div>
      </div>
      <div class="login-type" :style="{bottom: (leaderApply || storeApply) ? '350px' : '75px'}">
        <div class="account-login" @click="$pt.navigateTo({url: '/pages/home/account-login/main'})" v-if="!leaderApply && !storeApply">账号密码登录</div>
        <button
          v-if="!hasPhone"
          size="default"
          class="wechat-login phone-login"
          lang="zh_CN" 
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
        >
          微信一键登录
        </button>
        <div v-else class="wechat-login" @click="getUserProfile" >微信一键登录</div>
      </div>
      <div class="login-footer">
        <div class="login-agreement">
          登录代表您已阅读并同意
          <span @click="agreePrivacy">《隐私协议》</span>
          及
          <span @click="agreeUser">《会员协议》</span>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="get-user-info">
        <div class="align-c pad-l-30 pad-r-30 mar-l-15 mar-r-15">
          <div class="text-align-c phone-info">
            <div class="flex-center v-align-c height-96">
              <img v-if="appInfo.appLogo" class="width-96 height-96 avatar-bar" :src="appInfo.appLogo"/>
            </div>
            <div class="font-18 font-w mar-t-13">授权登录</div>
            <div class="font-15 font-color-9 mar-t-30 pad-t-16 mar-b-21">
              <div>为保障陛下您的体验旅程</div>
              <div>请先登录一下~</div>
            </div>
          </div>
          <div class='mar-t-20 width-per-100'>
            <button
              size="default"
              lang="zh_CN"
              class="primary-button font-17 font-w"
              open-type="getPhoneNumber"
              @getphonenumber="getPhoneNumber">
              朕允了
            </button>
            <div class="font-12 font-color-9 text-align-c agree-bar">
              登录表示您已同意
              <span class="pad-t-9 pad-b-9" @click="agreeUser">《用户协议》</span>
              和<span class="pad-t-9 pad-b-9" @click="agreePrivacy">《隐私协议》</span>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>
<script>
import { decrypt } from '@/api/wechat'
import { getAuth, checkMemberUnionId } from '@/api/login'
import { getMemberInfo, getCommanderApply, submitCommanderBindMember } from '@/api/home'
import { createMemberForAllinpay, checkPayMethod } from '@/api/pay'
import {
  setToken,
  setVeekrayStatus,
  setShowBuyCard,
  setPhone,
  setCustomerId,
  setCommanderStatus,
  setCommunityGroup,
  setEnterpriseId,
  setPayMethod } from '@/utils/auth'
export default {
  data() {
    return {
      hasPhone: false,
      nickname: '',
      avatarUrl: '',
      logoUrl: '',
      openId: '',
      commanderStatus: 0,
      veekrayStatus: 0,
      memberId: '',
      phone: '',
      leaderApply: false,
      storeApply: false,
      memberInfo: {},
      showBuyCard: true,
      bindRes: false,
      scanCodeBoolean: false
    }
  },
  computed: {
    appInfo() {
      return this.$store.state.appInfo
    }
  },
  mounted() {
    this.leaderApply = this.$pt.getStorageSync('leader-apply')
    this.storeApply = this.$pt.getStorageSync('store-apply')
    this.appInfo = this.$pt.getStorageSync('appInfo') || this.$store.state.appInfo
    this.scanCodeBoolean = Object.keys(this.$pt.getStorageSync('scanCode')).length
    this.getAuth()
  },
  methods: {
    getAuth() {
      this.$pt.login({
        success: res => {
          if (res.code) {
            getAuth(res.code).then((response) => {
              if (response.isError) return
              // 缓存customerId
              if (response.data.showBuyCard === false) {
                this.showBuyCard = false
                setShowBuyCard(response.data.showBuyCard)
                // 设置登录类型 1： 社群/团长身份登录 2：门店身份登录
                this.$pt.setStorageSync('loginType', 1)
                setCustomerId(this.appInfo.defaultMemberId)
                this.getMemberInfo()
                console.log('进了审核auth')
              }
              this.memberId = response.data.memberId
              this.memberId && this.$pt.setStorageSync('temporaryMemberId', this.memberId)
              // 缓存手机号
              this.phone = response.data.phone
              this.phone && this.$pt.setStorageSync('temporaryPhone', this.phone)
              // 缓存店长权限
              response.data.veekrayStatus && setVeekrayStatus(response.data.veekrayStatus)
              response.data.commanderStatus && setCommanderStatus(response.data.commanderStatus)
              this.openId = response.data.openId
              setShowBuyCard(response.data.showBuyCard)
              setToken(response.data.token)
              if (response.data.phone) {
                this.hasPhone = true
              }
            }).catch(() => {
            })
          }
        }
      })
    },
    async checkMemberUnionId(e) {
      // 校验该手机号是否有在顾客端授权过
      this.memberId = this.memberId || this.$pt.getStorageSync('temporaryMemberId')
      this.phone = this.phone || this.$pt.getStorageSync('temporaryPhone')
      if (this.memberId && this.phone) {
        await this.getMemberInfo()
        this.authority()
        return
      }
      // console.log('ssss', this.openId)
      let params = {
        enterpriseId: this.appInfo.enterpriseId,
        openId: this.openId,
        encryptedData: e.mp.detail.encryptedData,
        iv: e.mp.detail.iv
      }
      checkMemberUnionId(params).then(async response => {
        if (response.isError) return
        response.data.token && setToken(response.data.token)
        if (response.data.phone) {
          // setPhone(response.data.phone)
          this.phone = response.data.phone
          this.$pt.setStorageSync('temporaryPhone', this.phone)
          if (response.data.unionId && response.data.memberId) {
            // 已经授权过了
            this.memberId = response.data.memberId
            this.$pt.setStorageSync('temporaryMemberId')
            await this.getMemberInfo()
            this.authority()
            // setCustomerId(response.data.memberId)
            // this.$emit('updateAuth')
          } else if (!response.data.unionId && response.data.memberId) {
            // 去顾客端授权
            this.$pt.navigateToMiniProgram({appId: this.appInfo.shopAppId})
          } else {
            // 全新用户，授权用户头像昵称
            this.$pt.showModal({
              title: '',
              content: '为了更好的服务陛下，请先授权头像昵称',
              success: res => {
                if (res.confirm) {
                  this.getUserProfile()
                  this.hasPhone = true
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }
        }
      }).catch(() => {
      })
    },
    authority() {
      // 校验各种权限
      this.memberId = this.memberId || this.$pt.getStorageSync('temporaryMemberId')
      this.phone = this.phone || this.$pt.getStorageSync('temporaryPhone')
      let memberInfo = this.memberInfo
      // 判断是否有团长身份 1：有 0：没有
      if (memberInfo.commanderStatus === 1) {
        // 符合其中一个条件就是门店身份
        if (memberInfo.memberStore.isHomeDelivery === 1 || memberInfo.memberStore.isStoreExtraction === 1) {
          // 判断是否有门店到家增值功能 1：有  0：无
          if (this.appInfo.storeHomeAuthority === 1) {
            // 判断门店是否为启用状态 1：启用 0：禁用
            if (memberInfo.storeState === 1) {
              // 判断门店是否有社区团购业务 1：有 0：没有
              if (memberInfo.memberStore.isCommunityGroupExtraction === 1) {
                // 设置社区团购业务缓存
                setCommunityGroup(1)
              } else {
                // 设置社区团购业务缓存
                setCommunityGroup(0)
              }
              // 设置登录类型 1： 社群/团长身份登录 2：门店身份登录
              this.$pt.setStorageSync('loginType', 2)
              setCustomerId(this.memberId)
              setPhone(this.phone)
              this.$emit('updateAuth')
            } else {
              this.$utils.showToast({
                title: '门店已被禁用，无法登陆',
                duration: 3000
              })
            }
          } else {
            console.log('没有门店到家增值功能，提示系统到期')
            // 没有门店到家增值功能，提示系统到期
            this.$utils.showToast({
              title: '系统已过期',
              duration: 3000
            })
          }
        } else {
          // 否则就是社群团长身份
          // 判断是否有社区团购增值功能 1：有 0：无
          if (this.appInfo.groupBuyAuthority === 1) {
            // 社区团长是否为启用状态 1: 启用 0：禁用
            if (memberInfo.commanderEnable === 1) {
              if (this.$pt.getStorageSync('leader-applied')) {
                // 申请过社区团长，需要提示
                this.getCommanderApply()
              } else {
                this.$pt.setStorageSync('loginType', 1)
                setCustomerId(this.memberId)
                setPhone(this.phone)
                this.$emit('updateAuth')
              }
            } else {
              this.$utils.showToast({
                title: '团长已被禁用，无法登陆',
                duration: 3000
              })
            }
          } else {
            console.log('没有社区团购增值功能，提示系统到期')
            // 没有社区团购增值功能，提示系统到期
            this.$utils.showToast({
              title: '系统已过期',
              duration: 3000
            })
          }
        }
      } else {
        // 没有团长身份，判断是否有社群分销店主身份
        if (this.getVeekrayStatus === 1) {
          setCustomerId(this.memberId)
          setPhone(this.phone)
          this.$emit('updateAuth')
        } else {
          // 判断是否有社区团购增值功能 1：有 0：无
          if (this.appInfo.groupBuyAuthority === 1) {
            // 判断是否申请过团长 true: 有 false：无
            if (this.$pt.getStorageSync('leader-applied')) {
              // 查询申请团长结果
              this.getCommanderApply()
            } else {
              if (this.$pt.getStorageSync('bindCommander')) {
                this.bindCommander()
              } else {
                // 没有申请过团长，去团长申请页
                this.$pt.navigateTo({ url: `/pages/home/leader-apply/main?phone=${this.phone}&memberId=${this.memberId}` })
              }
            }
          } else {
            console.log('9999', this.$pt.getStorageSync('bindCommander'), this.memberId)
            // 没有社区团购增值功能
            const scanIn = this.$pt.getStorageSync('scanIn')
            const scanCode = this.$pt.getStorageSync('scanCode')
            if (scanIn && scanCode) {
              setCustomerId(this.memberId)
              setPhone(this.phone)
              setEnterpriseId(this.appInfo.enterpriseId)
              setTimeout(() => {
                this.$pt.reLaunch({
                  url: '/pages/home/get-card/main?salesData=' + scanCode
                })
              }, 300)
              return
            }
            if (this.$pt.getStorageSync('bindCommander')) {
              this.bindCommander()
            } else {
              // 判断是否开启云店申请的Banner图入口 1：开启 0：禁用
              // console.log('111 店铺审核中')
              if (this.$pt.getStorageSync('unshoper')) {
                this.$pt.reLaunch({
                  url: '/pages/order/apply-for/main?enterpriseType=3&veekrayStatus=' + this.$pt.getStorageSync('veekrayStatus')
                })
                return
              }
              setCustomerId(this.memberId)
              setPhone(this.phone)
              setEnterpriseId(this.appInfo.enterpriseId)
              this.$pt.navigateTo({ url: '/pages/home/apply-shopowner/main' })
            }
          }
        }
      }
    },
    bindCommander() {
      let scanCode = this.$pt.getStorageSync('scanCode')
      let memberId = this.memberId || this.$pt.getStorageSync('temporaryMemberId')
      submitCommanderBindMember({
        memberId: memberId,
        enterpriseId: scanCode.enterpriseId,
        commanderId: scanCode.commanderId
      }).then(response => {
        if (response.isError) return
        this.$pt.reLaunch({ url: '/pages/home/apply-result/main?memberId=' + memberId + '&phone=' + this.phone + '&bindStatus=1' })
      }).catch(() => {
      })
    },
    async getUserProfile() {
      this.memberId = this.memberId || this.$pt.getStorageSync('temporaryMemberId')
      this.phone = this.phone || this.$pt.getStorageSync('temporaryPhone')
      if (this.memberId && this.phone) {
        await this.getMemberInfo()
        this.authority()
        return
      }
      // 获取会员信息
      this.$pt.getUserProfile({
        desc: '用于完善会员资料',
        success: res => {
          this.nickname = res.userInfo.nickName
          this.avatarUrl = res.userInfo.avatarUrl
          // 保存unionId，同时插入/更新会员信息
          let data = {
            memberId: this.memberId || '', // getCustomerId可为空值
            phone: this.phone,
            encryptedData: res.encryptedData,
            iv: res.iv,
            type: 2
          }
          if (!res.encryptedData) {
            this.$emit('lowVersion')
            this.$pt.showModal({
              title: '提示',
              content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
            return
          }
          decrypt(data).then(async response => {
            // 执行登录
            if (response.data.memberId) {
              this.checkPayMethod(response.data.memberId)
              this.memberId = response.data.memberId
              this.phone = response.data.phone
              // setCustomerId(response.data.memberId)
              response.data.token && setToken(response.data.token)
              await this.getMemberInfo()
              this.authority()
            }
          }).catch(() => {
          })
        }
      })
    },
    checkPayMethod(customerId) {
      checkPayMethod({
        memberId: customerId
      }).then((response) => {
        if (response.data) {
          setPayMethod(response.data)
          if (response.data === 2) {
            this.createMemberForAllinpay(customerId)
          }
        } else {
          setPayMethod(1)
        }
      }).catch(() => {
      })
    },
    createMemberForAllinpay(customerId) {
      createMemberForAllinpay({
        memberId: customerId
      }).then((response) => {
      }).catch(() => {
      })
    },
    getPhoneNumber(e) {
      if (e) {
        if (e.mp.detail.encryptedData) {
          // 保存电话号码
          // console.log(e)
          // 校验该手机号是否有在顾客端授权过
          this.checkMemberUnionId(e)
        } else {
          this.$pt.showModal({
            title: '温馨提示',
            content: '该appId没有权限，请前往微信认证',
            success: res => {
            }
          })
        }
      }
    },
    getMemberInfo() {
      this.memberId = this.memberId || this.$pt.getStorageSync('temporaryMemberId')
      let memberId = this.showBuyCard ? this.memberId : this.appInfo.defaultMemberId
      return new Promise((resolve, reject) => {
        getMemberInfo(memberId).then(response => {
          if (response.isError) return
          if (this.showBuyCard === false) {
            setPhone(response.data.phone)
            this.$emit('updateAuth')
          }
          this.memberInfo = response.data
          this.avatarUrl = response.data.avatar
          this.nickName = response.data.nickname
          response.data.veekrayStatus && setVeekrayStatus(response.data.veekrayStatus)
          response.data.commanderStatus && setCommanderStatus(response.data.commanderStatus)
          // console.log('3333 veekrayStatus', response.data.veekrayStatus)
          resolve(true)
        }).catch(() => {})
      })
    },
    agreeUser() {
      this.$pt.navigateTo({url: '/pages/home/agree-user/main'})
    },
    agreePrivacy() {
      this.$pt.navigateTo({url: '/pages/home/agree-privacy/main'})
    },
    getCommanderApply() {
      // 查询申请团长结果
      this.memberId = this.memberId || this.$pt.getStorageSync('temporaryMemberId')
      this.phone = this.phone || this.$pt.getStorageSync('temporaryPhone')
      getCommanderApply({
        memberId: this.memberId
      }).then(response => {
        if (response.isError) return
        let status = response.data.status
        if (status === 1) {
          this.$utils.showToast({
            title: '团长申请成功',
            duration: 3000
          })
          setTimeout(() => {
            setCustomerId(this.memberId)
            setPhone(this.phone)
            this.$pt.removeStorageSync('applyStore')
            this.$pt.removeStorageSync('leader-applied')
            this.$emit('updateAuth')
          }, 3000)
        } else if (status === 2) {
          this.$utils.showToast({
            title: '团长申请失败',
            duration: 3000
          })
          setTimeout(() => {
            this.$pt.navigateTo({ url: `/pages/home/leader-apply/main?phone=${this.phone}&memberId=${this.memberId}` })
          }, 3000)
        } else if (status === 0) {
          this.$utils.showToast({
            title: '团长申请审核中',
            duration: 3000
          })
        } else {
          this.$utils.showToast({
            title: '团长出错，请重新申请',
            duration: 3000
          })
          setTimeout(() => {
            this.$pt.navigateTo({ url: `/pages/home/leader-apply/main?phone=${this.phone}&memberId=${this.memberId}` })
          }, 3000)
        }
      }).catch(() => {
      })
    }
  }
}
</script>
<style lang="less" scoped>
.get-user-info {
  // width: 375px;
  // height: calc(100vh);
  // background-color: #fff;
  // overflow: hidden;
  .phone-info{
    // margin-top: 135px;
    &.other-page{
      margin-top: 75px;
    }
  }
  .avatar-bar{
    border-radius: 100px;
  }
  .primary-button{
    background: #ff1717;
    color: #fff;
    border-radius: 50px;
    margin-top: 30px;
    padding: 1px 0;
  }
  .agree-bar{
    span{
      display: inline-block;
      color: #5876B3;
    }
  }
  .top-nav{
    background: #ffffff;
    color: #333;
    box-sizing: border-box;
    text-align: center;
    font-size: 15px;
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 100;
    .top-txt{
      font-size: 18px;
      color: #333;
    }
  .self-back {
    width: 20rpx;
    height: 20rpx;
    border-top: 2px solid #000;
    border-left: 2px solid #000;
    transform: rotate(-45deg);
    position: absolute;
    left: 20rpx;
  }
  }
}
.user-login{
  padding-top: 75px;
  width: 100%;
  background-color: #FFF;
  box-sizing: border-box;
  min-height: 100vh;
  position: fixed;
  z-index: 999;
  .img-logo{
    width: 84px;
    height: 84px;
    border-radius: 50%;
    margin: 40px auto 0;
  }
  .logo-text{
    text-align: center;
    font-size: 30px;
    font-weight: bold;
    color: #666;
    margin-top: 14px;
  }
  .login-type{
    position: absolute;
    bottom: 75px;
    left: 0;
    width: 100%;
    .account-login{
      width: 290px;
      height: 45px;
      line-height: 45px;
      text-align: center;
      position: relative;
      color: #FF1717;
      font-size: 16px;
      font-weight: bold;
      margin: 0 auto;
      &::after{
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 200%;
        height: 200%;
        border: 1px solid #FF1717;
        border-radius: 44px;
        transform: scale(.5);
        -webkit-transform-origin: top left;
        box-sizing: border-box;
      }
    }
    .wechat-login{
      margin: 30px auto 0;
    }
  }
  .login-footer{
    position: absolute;
    bottom: 20px;
    left: 0;
    width: 100%;
    .login-agreement{
      color: #999;
      text-align: center;
      font-size: 12px;
      margin-top: 34px;
      span{
        color: #FF1717;
      }
    }
  }
  .wechat-login{
    width: 290px;
    height: 45px;
    line-height: 45px;
    text-align: center;
    border-radius: 22px;
    background-color: #FF1717;
    font-size: 16px;
    color: #FFF;
    margin: 52px auto 0;
  }
  .phone-login{
    &::after{
      border: unset;
    }
  }
}
</style>
